home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12911 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: tertio.co.uk!alord
  2. From: alord@tertio.co.uk ()
  3. Newsgroups: comp.lang.c,comp.unix.programmer
  4. Subject: Re: Q: '\n' character - strtok trick
  5. Date: Wed, 03 Apr 1996 14:41:14 GMT
  6. Organization: Personal
  7. Message-ID: <828542474.7672@tertio.demon.co.uk>
  8. References: <31616F63.481D@lava.weeg.uiowa.edu> <4jrvv3$ask@aimnet.aimnet.com> <828493319snz@genesis.demon.co.uk>
  9. Reply-To: Andrew_Lord@tertio.co.uk (Andrew Lord)
  10. NNTP-Posting-Host: tertio.demon.co.uk
  11. X-NNTP-Posting-Host: tertio.demon.co.uk
  12. X-Newsreader: slrn (0.7.6.0)
  13.  
  14. In article <828493319snz@genesis.demon.co.uk>, Lawrence Kirby  wrote:
  15. >
  16. >>In article <31616F63.481D@lava.weeg.uiowa.edu>,
  17. >>Artur Wojdat  <awojdat@lava.weeg.uiowa.edu> wrote:
  18. >>
  19. >>>       Is there a function or some sort of way that I could remove '\n' 
  20. >>>charecter form the end of the string. I'm reading from two files, want to 
  21. >>>form one line of text and then have it printed out to stdout. I use fgets to 
  22. >>>read from the file and I noticed that it appends newline char at the end.
  23. >
  24. >There is a simple trick to remove any trailing newline character in a string
  25. >typically written by fgets(), say into buffer,  and that is:
  26. >
  27. >   strtok(buffer, "\n");
  28. >
  29. At the risk or embarassing myself infront someone who probably knows a lot more
  30. about the C languange than myself -
  31.  
  32. Although the behaviour of strtok() is well defined I try to avoid it like the
  33. plague because it uses a static area to maintain state. If another function
  34. happens to call it between successive invocations then your screwd.
  35.  
  36. Having said that, it is obvious that this example is a one-off call to strtok
  37. and that it is described as a 'trick'. And I have to confess that I like it!
  38.  
  39. It would have to be commented though because you are using the side-effect of
  40. a function to achieve you primary objective? Other people (of varying ability)
  41. may have to maintain it.
  42.  
  43.     strtok(buffer,'\n'); /* Remove '\n' */
  44.  
  45. Is a pleasant improvement on my old way of doing it.
  46. I used to use
  47.     if ((p = strchr(buffer,'\n')) != NULL ) *p = '\0';
  48.  
  49. where p is a 'char *' somewhere, but no more!
  50.  
  51. Would I be correct in saying avoid using strtok to repeatedly extract tokens
  52. unless you can guarantee that it will NEVER be called elsewhere in the code
  53. between your own invocations - and such guarantees are hard to make?
  54.  
  55. Andy L.
  56.  
  57.  
  58.  
  59.